import { getUuid } from "@/utils/common.methods";
import { SessionInfo, SiderMenuEnum } from "./@types";
import { Message } from "@arco-design/web-vue";
import { chatDB } from "@/db/chat";
import { SyncActionEnum, synchronousService } from "@/services/synchronous.service";

export type MindMapInfo = {
  uid: string;
  label: string;
  type: SiderMenuEnum;
  originalWords?: string;
  value?: string;
  childrens?: MindMapInfo[];
};

export type ChatFileInfo = {
  currKey?: string;
  menus?: MindMapInfo[];
};

export class MindMapModel {
  public LOCAL_STORAGE_KEY = "chat-mindmap";
  private _data = <ChatFileInfo>{};

  constructor() {}

  public async setData(): Promise<void> {
    let dataStr = (await chatDB.getStr(this.LOCAL_STORAGE_KEY))?.value ;
    this._data = dataStr ? JSON.parse(dataStr) : {};
  }

  /** 左侧目录 */
  public async menus(): Promise<MindMapInfo[]> {
    if (!this._data?.currKey) {
      await this.setData();
    }
    return this._data?.menus || [];
  }

  public async add(type: SiderMenuEnum, parent?: string): Promise<void> {
    const label = (type === SiderMenuEnum.Group ? "合集" : "会话") + getUuid(5);
    const uid = getUuid();
    const item: MindMapInfo = { uid, label, type };
    if (parent) {
      this._data?.menus?.map((val) => {
        if (val.uid === parent) {
          val.childrens = (val.childrens || []).concat(item);
        }
        return val;
      });
    } else {
      this._data = {
        currKey: uid,
        menus: (this._data?.menus || []).concat(item),
      };
    }
    synchronousService.session(this.LOCAL_STORAGE_KEY, SyncActionEnum.Add, item, parent);
    await this.setLocalStorage("add");
  }

  public async updateEmuse(menus: MindMapInfo[]) {
    this._data.menus = menus;
    await this.setLocalStorage("update");
  }

  public async edit(uid: string, label: string): Promise<void> {
    let item = {} as MindMapInfo;
    let parent = undefined;
    this._data.menus?.forEach((menu) => {
      if (menu.uid === uid) {
        menu.label = label;
        item = menu;
      }
      menu.childrens?.forEach((child) => {
        if (child.uid === uid) {
          child.label = label;
          item = child;
          parent = menu.uid;
        }
      });
    });
    synchronousService.session(this.LOCAL_STORAGE_KEY, SyncActionEnum.Update, item, parent);

    await this.setLocalStorage("edit");
  }

  public async remove(uid: string): Promise<void> {
    this._data.menus = this._data.menus?.filter((val) => {
      val.childrens = val.childrens?.filter((child) => child.uid !== uid);
      return val.uid !== uid;
    });
    this._data.currKey = this._data.menus[0]?.uid || "";
    synchronousService.session(this.LOCAL_STORAGE_KEY, SyncActionEnum.Delete, { uid } as MindMapInfo);
    await this.setLocalStorage("remove");
  }

  public async setCurrKey(uid: string): Promise<void> {
    this._data.currKey = uid;
    await this.setLocalStorage("setCurrKey");
  }

  public get currKey(): string {
    return this._data?.currKey;
  }

  public get currMenu(): MindMapInfo {
    if (!this._data?.menus?.length) return;
    const key = this.currKey;
    for (const item of this._data?.menus) {
      if (item.uid === key) {
        return item;
      } else {
        if (item?.childrens) {
          for (const child of item?.childrens) {
            if (child.uid === key) return child;
          }
        }
      }
    }
    return null;
  }

  public async update(originalWords: string, value: string): Promise<void> {
    let item = {} as MindMapInfo;
    let parent = undefined;
    const key = this._data.currKey;
    for (const menu of this._data.menus) {
      if (menu.uid === key) {
        menu.label = originalWords.slice(0, 10);
        menu.originalWords = originalWords;
        menu.value = value;
        item = menu;
      }
      if (menu?.childrens) {
        for (const child of menu?.childrens) {
          if (child.uid === key) {
            child.label = originalWords.slice(0, 10);
            child.originalWords = originalWords;
            child.value = value;
            item = child;
            parent = menu.uid;
          }
        }
      }
    }
    synchronousService.session(this.LOCAL_STORAGE_KEY, SyncActionEnum.Update, item, parent);
    await this.setLocalStorage("updateImage");
  }

  /** 清空 */
  public async clear(): Promise<void> {
    this._data = {};
    synchronousService.clearSession(this.LOCAL_STORAGE_KEY);
    await this.setLocalStorage("clear");
  }

  private async setLocalStorage(source: string): Promise<void> {
    console.log("setLocalStoragesetloca >>> source :", source, this._data);
    await chatDB.set(this.LOCAL_STORAGE_KEY, JSON.stringify(this._data));
    //  localStorage.setItem(this.LOCAL_STORAGE_KEY, JSON.stringify(this._data));
  }
}
